suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(ChIPseeker))
suppressPackageStartupMessages(library(clusterProfiler))
suppressPackageStartupMessages(library(argparse))

parser <- ArgumentParser()
parser$add_argument("-i", "--peak_file", help="peak file")
parser$add_argument("-o", "--anno_file", help="annotate peak file")
parser$add_argument("-s", "--species", default="hs", help="species hs|mm|rn (default='hs')")
args <- parser$parse_args()

if (args$species == "hs") {
  suppressPackageStartupMessages(library(TxDb.Hsapiens.UCSC.hg38.knownGene))
  txdb <- TxDb.Hsapiens.UCSC.hg38.knownGene
  annoDb <- "org.Hs.eg.db"
} else if (args$species == "mm") {
  suppressPackageStartupMessages(library(TxDb.Mmusculus.UCSC.mm10.knownGene))
  txdb <- TxDb.Mmusculus.UCSC.mm10.knownGene
  annoDb <- "org.Mm.eg.db"
} else if (args$species == "rn") {
  suppressPackageStartupMessages(library(TxDb.Rnorvegicus.UCSC.rn6.refGene))
  txdb <- TxDb.Rnorvegicus.UCSC.rn6.refGene
  annoDb <- "org.Rn.eg.db"
}

peakAnno <- annotatePeak(args$peak_file, tssRegion=c(-3000, 3000), TxDb=txdb, annoDb=annoDb)

if (grepl(".xlsx$", args$anno_file)) {
  as.data.frame(peakAnno) %>% writexl::write_xlsx(args$anno_file)
} else {
  as.data.frame(peakAnno) %>%
    write.table(args$anno_file, sep="\t", quote=FALSE, row.names = FALSE)
}

